#include "util.hpp"
#include <cstdio>
#include <vector>
#include <functional>
#include <sys/select.h>

using  func_t=std::function<void()>;

#define INIT(v) do \
{\
    v.push_back(printLog);\
} while (0);

#define EXEC_OTHER(cbs)            \
    do                             \
    {                              \
        for (auto const &cb : cbs) \
            cb();                  \
    } while (0)

int main()
{
    std::vector<func_t> cbs;
    INIT(cbs);

    setNonBlock(0);//将标准输入流设置非阻塞
    char buffer[1024];
    while (true)
    {
        ssize_t s=read(0,buffer,sizeof(buffer)-1);
        if(s>0)
        {
            buffer[s-1]=0;
            std::cout<<"echo# "<<buffer<<std::endl;
        }
        else if(s==0)//ctrl+d触发
        {
            std::cout << "read end" << std::endl;
            break;
        }
        else
        {
            if(errno==EAGAIN)//EAGAIN:11
            {
                std::cout<<"我没有错误，上层没有输入数据"<<std::endl;
                EXEC_OTHER(cbs);
            }
            else if(errno==EINTR)//被中断，不算错误，重新读
            {
                continue;
            }
            else//错误
            {
                std::cout << "s : " << s << " errno: " << strerror(errno) << std::endl;
                break;
            }
        }

        sleep(1);
    }
    
    
}